package com.woniuxy.dudugua.util.cancelUtil;

import com.woniuxy.dudugua.entity.Order;
import com.woniuxy.dudugua.entity.ReturnGoods;
import com.woniuxy.dudugua.mapper.OrderMapper;
import com.woniuxy.dudugua.mapper.ReturnGoodsMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.relational.core.sql.In;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    private final static Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);


    /**
     * Creates new {@link MessageListener} for {@code __keyevent@*__:expired} messages.
     *
     * @param listenerContainer must not be {@literal null}.
     */
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();

        if(expiredKey.contains("accept=")){
            //包含了accept，截取=后面的，就是orderid
           String oId= expiredKey.split("=")[1];
           Integer orderId= Integer.parseInt(oId);
            Order order = orderMapper.selectByPrimaryKey(orderId);
            order.setStatus(6);
            orderMapper.updateByPrimaryKey(order);
            log.info("自动收货");
        }
        if(expiredKey.contains("order=")){
            //自动取消订单
            String oId= expiredKey.split("=")[1];
            Integer orderId= Integer.parseInt(oId);
            Order order = orderMapper.selectByPrimaryKey(orderId);
            order.setStatus(5);
            orderMapper.updateByPrimaryKey(order);
            log.info("自动取消订单");
        }
        if(expiredKey.contains("return=")){
            //两天之后自动同意退货
            String rId= expiredKey.split("=")[1];
            Integer returnId= Integer.parseInt(rId);
            ReturnGoods returnGoods = returnGoodsMapper.selectByPrimaryKey(returnId);
            returnGoods.setStatus(5);
            returnGoodsMapper.updateByPrimaryKey(returnGoods);
        }
    }
}
